package org.dk.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.dk.mapper.TbItemCatMapper;
import org.dk.pageInfo.PageInfo2;
import org.dk.pojo.TbItemCat;
import org.dk.pojo.TbItemCatExample;
import org.dk.service.TbItemCatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@com.alibaba.dubbo.config.annotation.Service
public class TbItemCatServiceImpl implements TbItemCatService {

    @Autowired
    private TbItemCatMapper tbItemCatMapper;
    @Override
    public PageInfo2<TbItemCat> select(Integer pageNum, Integer pageSize, Long id) {
        PageHelper.startPage(pageNum,pageSize);
        PageInfo<TbItemCat> pageInfo = new PageInfo<>(tbItemCatMapper.selectByparentid(id));
        PageInfo2<TbItemCat> pageInfo1 = new PageInfo2();
        pageInfo1.setPageNum(pageInfo.getPageNum());
        pageInfo1.setPageSize(pageInfo.getSize());
        pageInfo1.setTotal(pageInfo.getTotal());
        pageInfo1.setList(pageInfo.getList());
        pageInfo1.setLastPage(pageInfo.getPages());
        return pageInfo1;
    }

    @Override
    public TbItemCat selectById(Long parentId) {
        TbItemCat tbItemCat = tbItemCatMapper.selectByPrimaryKey(parentId);
        return tbItemCat;
    }

    @Override
    public void addItemCat(TbItemCat itemCat) {
        tbItemCatMapper.insertSelective(itemCat);
    }

    @Override
    public void deleteItemType(Long[] ids) {
        //先删最大的
        tbItemCatMapper.deleteItemType(ids);
        //ids = parent_id ~ 的id = parent_id
        for (int i = 0; i < ids.length ; i++) {
            TbItemCatExample tbItemCatExample = new TbItemCatExample();
            TbItemCatExample.Criteria criteria = tbItemCatExample.createCriteria();
            criteria.andParentIdEqualTo(ids[i]);
            //根据最大的查出儿子
            List<TbItemCat> tbItemCats = tbItemCatMapper.selectByExample(tbItemCatExample);
            for (int j = 0; j < tbItemCats.size(); j++) {
                //删儿子
                tbItemCatMapper.delteTtem(ids[i]);
                //删孙子
                tbItemCatMapper.delteTtem(tbItemCats.get(i).getId());
            }

        }
    }

    @Override
    public TbItemCat updateItemCatReturn(Long id) {
        return tbItemCatMapper.selectByPrimaryKey(id);
    }

    @Override
    public void updateItemType(TbItemCat itemCat) {
        tbItemCatMapper.updateByPrimaryKeySelective(itemCat);
    }

    @Override
    public List<TbItemCat> selectByParentId(Long parentId) {
        TbItemCatExample example = new TbItemCatExample();
        TbItemCatExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        return tbItemCatMapper.selectByExample(example);
    }

    @Override
    public List<TbItemCat> selectAll() {
        return tbItemCatMapper.selectByExample(new TbItemCatExample());
    }
}
